package com.qst.service.ssm;

import com.qst.ExamException;
import com.qst.entity.TestPersonnel;
import com.qst.entity.User;
import com.qst.mapper.TestPersonnelMapper;
import com.qst.mapper.UserMapper;
import com.qst.service.TestPersonnelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
@SuppressWarnings("all")
public class TestPersonnelSsmServiceImpl implements TestPersonnelService {

    @Autowired
    private  TestPersonnelMapper personnelMapper;
    @Autowired
    private  UserMapper userMapper;

    @Override
    public TestPersonnel findById(int id) {
        return personnelMapper.findById(id);
    }

    @Override
    public List<TestPersonnel> findByTeamId(int tid) {
        return personnelMapper.findByTeam(tid);
    }

    @Override
    public List<TestPersonnel> query(int teamId, String name, String phone) {
        return personnelMapper.query(teamId,name,phone);
    }

    @Override
    public void addTestPersonnel(TestPersonnel s) {
        User u = s.getUser();
        if (u.getType() == 0) {
            u.setType(4);
        }
        u.setStatus(1);
        if (u.getPasswd() == null || u.getPasswd().equals("")) {
            u.setPasswd(User.PASSWORD);
        }
        u.setLogin(s.getPhone());
        userMapper.insertUser(u);
        s.setId(u.getId());
        personnelMapper.insert(s);
    }

    @Override
    public void importTestPersonnel(List<TestPersonnel> testPersonnelList) {
        for (int i = 0; i < testPersonnelList.size(); i++) {
            TestPersonnel s = testPersonnelList.get(i);
            TestPersonnel temp = personnelMapper.findByPhone(s.getPhone());
            if (temp == null)
            {
                addTestPersonnel(s);
            } else
            {
                if (temp.getTeamId() != s.getTeamId()) {
                    throw new ExamException("导入第" + (i + 1) + "个参测人员出错,该手机号"
                            + s.getPhone() + "已在其他参测人员注册");
                }
                s.setId(temp.getId());
                updateTestPersonnel(s);

            }
        }
    }

    @Override
    public void updateTestPersonnel(TestPersonnel s) {
        User user = s.getUser();
        User u = userMapper.findUserById(s.getId());
        u.setName(user.getName());
        if (user.getStatus() != 0) {
            u.setStatus(user.getStatus());
        }
        userMapper.updateUser(u);
        personnelMapper.update(s);
    }

    @Override
    public TestPersonnel deleteTestPersonnel(int id) {
        User user = userMapper.findUserById(id);
        if (user.getLastLogin() != null) {
            throw new ExamException("该账户已启用，不能删除");
        }
        TestPersonnel testPersonnel = personnelMapper.findById(id);
        personnelMapper.delete(id);
        userMapper.delUserById(id);

        testPersonnel.setUser(user);
        return testPersonnel;
    }
}
